package cn.nextProject.controller;

import cn.nextProject.Utils.CommonUtils;
import cn.nextProject.entity.Result;
import cn.nextProject.entity.flowable.TaskDTO;
import cn.nextProject.entity.req.StartTask;
import cn.nextProject.service.TaskService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;
import sun.text.resources.FormatData;

import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class TaskController {

    @Autowired
    private TaskService taskService;

    /**
     * 获取用户的发起任务
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/getMyTasks")
    public Result<?> getMyTasks(@RequestParam("pageNum")int pageNum,
                                @RequestParam("pageSize")int pageSize){

        String username = CommonUtils.getToken();
        if (ObjectUtils.isEmpty(username)){
            return new Result<>().fail("用户未登录！");
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Task> myTasks = taskService.getMyTasks(username);
        PageInfo<Task> pageInfo = new PageInfo<>(myTasks);

        return new Result<>().success("查询成功",pageInfo.getList(),pageInfo.getTotal());

    }

    @PostMapping("/startTask")
    public Result<?> startTask(@RequestBody TaskDTO taskDTO) {

        String processDefinitionId = taskDTO.getProcessInstanceId();
        Map<String, Object> variables = taskDTO.getVariables();

        if (processDefinitionId == null){
            return new Result<>().fail("流程定义ID不能为空");
        }
        if (CollectionUtils.isEmpty(variables)){
            return new Result<>().fail("表单数据不能为空");
        }

        Map<Integer, Object> integerObjectMap = taskService.startTask(processDefinitionId, variables);
        if (ObjectUtils.isEmpty(integerObjectMap.get(0))){
            return new Result<>().success("任务启动成功！", null);
        }else{
            return new Result<>().fail(integerObjectMap.get(0).toString());
        }

    }


}
